package com.zoweunion.mechanic.service.base.impl;

import com.alibaba.fastjson.JSON;
import com.zoweunion.mechanic.dao.FacilitatorPersonnelRelationDao;
import com.zoweunion.mechanic.dao.base.MessageRecordDao;
import com.zoweunion.mechanic.dao.base.UserDao;
import com.zoweunion.mechanic.entity.ThingsIdCarRecordBean;
import com.zoweunion.mechanic.plugins.mq.RabbitMQCustomer;
import com.zoweunion.mechanic.service.base.BaseService;
import com.zoweunion.mechanic.dao.base.LockCarMapper;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.model.app.ApplicationUnlock;
import com.zoweunion.mechanic.model.app.LockCar;
import com.zoweunion.mechanic.plugins.jpush.JiguangPush;
import com.zoweunion.mechanic.service.base.LockCarService;
import com.zoweunion.mechanic.util.*;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.constants.PushConstants;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Service
public class LockCarServiceImpl extends BaseService implements LockCarService {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    LockCarMapper lockCarMapper;

    @Autowired
    private JiguangPush jiguangPush;

    @Autowired
    private EngineLockCarServiceImpl engineLockCarService;

    @Autowired
    private RabbitMQCustomer rabbitMQCustomer;

    @Autowired
    private FacilitatorPersonnelRelationDao facilitatorPersonnelRelationDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private MessageRecordDao messageRecordDao;

    @Override
    public Map<String, Object> getLockVehicleList(User currentUser, Map<String, Object> reqMap) {
        Map<String, Object> resultMap = new HashMap<>();

        if (Constants.ROLE_CZ.equals(currentUser.getR_id())) {
            reqMap.put("searchGLY", false);
        } else if (Constants.ROLE_GLY.equals(currentUser.getR_id()) || Constants.ROLE_GG.equals(currentUser.getR_id())) {
            reqMap.put("s_id", currentUser.getS_id());
            reqMap.put("searchGLY", true);
        }
        List<Map<String, Object>> list  = lockCarMapper.getLockVehicleList(reqMap);
        resultMap.put("list", list);
        resultMap.put("r_id", currentUser.getR_id());
        return resultMap;
    }

    @Override
    public List<Map<String, Object>> getApplicationUnlockList(User currentUser, Map<String, Object> reqMap) {
        String lockCarId = reqMap.get("lock_car_id").toString();
        return lockCarMapper.getApplicationUnlockList(lockCarId);
    }

    @Override
    public Map<String, Object> getLockCar(User currentUser, LockCar lockCar) throws MyException {
        Map<String, Object> resultMap = new HashMap<>(3);
        LockCar lockCarS = lockCarMapper.getLockCarByCarId(lockCar.getCarId());
        if(lockCarS!=null){
            lockCarS.setOneLevelDelayTime(DateUtil.formatTime(DateUtil.parseTime(lockCarS.getCreateTime()).plusMinutes(Integer.valueOf(lockCarS.getOneLevelDelay()))));
            lockCarS.setTwoLevelDelayTime(DateUtil.formatTime(DateUtil.parseTime(lockCarS.getCreateTime()).plusMinutes(Integer.valueOf(lockCarS.getTwoLevelDelay()) + Integer.valueOf(lockCarS.getOneLevelDelay()))));
            lockCarS.setThreeLevelDelayTime(DateUtil.formatTime(DateUtil.parseTime(lockCarS.getCreateTime()).plusMinutes(Integer.valueOf(lockCarS.getThreeLevelDelay()) + Integer.valueOf(lockCarS.getTwoLevelDelay()) + Integer.valueOf(lockCarS.getOneLevelDelay()))));
            List<ApplicationUnlock> applicationUnlockList = lockCarMapper.getApplicationUnlock(lockCarS.getCarId(), lockCarS.getId());
            resultMap.put("lockCar", lockCarS);
            resultMap.put("applicationUnlockList", applicationUnlockList);
            int setReaded = lockCarMapper.setReaded(lockCar.getCarId());
        }
        return resultMap;
    }

    /**
     * 锁车
     *
     * @param currentUser
     * @param lockCar
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void lockCar(User currentUser, LockCar lockCar) throws MyException {
        boolean isEdit = StringUtils.isNotBlank(lockCar.getId());
        // 获取被锁车信息
        LockCar lockCarV = lockCarMapper.getLockCarByCarId(lockCar.getCarId());

        // 如果车子已经被锁
        if (lockCarV != null && LockCar.LOCK_STATUS_LOCKED.equals(lockCarV.getIsLock())) {
            throw new MyException(Constants.CODE_SUCCESS, "该车辆已经被锁");
        }

        if (lockCarV == null || LockCar.LOCK_STATUS_NOLOCK.equals(lockCarV.getIsLock())) {
            lockCar.setId(UuidUtil.get32UUID());
            lockCar.setIsLock(LockCar.LOCK_STATUS_LOCK);
            lockCar.setCreateTime(currentUser.getId());
            lockCar.setCreateUser(currentUser.getId());
        }

        LocalDateTime dateTime = LocalDateTime.now();

        String lockDelay = lockCar.getLockDelay();

        if (!"0".equals(lockDelay)) {
            dateTime = dateTime.plusMinutes(Long.valueOf(lockDelay));
        }
        lockCar.setLockTime(dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        lockCar.setUpdateUser(currentUser.getId());
        // 设置指令执行状态
        lockCar.setExecuteStatus(LockCar.EXECUTE_STATUS_PROCESS);
        // 如果重新开始锁车
        if (isEdit) {
            lockCarMapper.updateLockTime(lockCar);
            lockCarMapper.updateCarIsLoeckByCarId(lockCar.getCarId(), LockCar.LOCK_STATUS_LOCK);
        } else {
            lockCarMapper.saveLockCar(lockCar);
            lockCarMapper.updateCarIsLoeckByCarId(lockCar.getCarId(), LockCar.LOCK_STATUS_LOCK);
        }
        // hasLockCar   状态值 0-没有锁车功能 1-普通锁车 2-继电器锁车
        String hasLockCar = lockCarMapper.getHasLockCar(lockCar.getCarId());
        if ("1".equals(hasLockCar)) {
            // 普通锁车 发送即时信息
            this.sendMessageWarningLockCarImmediately(lockCar);
        } else if ("2".equals(hasLockCar)) {
            this.sendMessageWarningRelaylLockCar(lockCar);
        }
    }

    /**
     * 解锁
     *
     * @param currentUser
     * @param lockCar
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unlockCar(User currentUser, LockCar lockCar) {
        lockCar.setUnlockTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        lockCar.setUpdateUser(currentUser.getId());
        lockCar.setExecuteStatus(LockCar.EXECUTE_STATUS_CANCEL_PROCESS_UNLOCK);
        lockCarMapper.saveUnLockCar(lockCar);
        lockCarMapper.updateCarIsLoeckByCarId(lockCar.getCarId(), LockCar.LOCK_STATUS_NOLOCK);

        /*String hasLockCar = lockCarMapper.getHasLockCar(lockCar.getCarId());
        if ("1".equals(hasLockCar)) {
            // 给车主和司机发送解锁码
            this.sendUnlockCode(lockCar.getCarId());
        }*/
    }

    /**
     * 取消锁车
     *
     * @param currentUser
     * @param lockCar
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelLockCar(User currentUser, LockCar lockCar) {
        // 设置指令取消
        lockCar.setExecuteStatus(LockCar.EXECUTE_STATUS_CANCEL_PROCESS);
        lockCar.setUpdateUser(currentUser.getId());
        lockCarMapper.saveUnLockCar(lockCar);
        lockCarMapper.updateCarIsLoeckByCarId(lockCar.getCarId(), LockCar.LOCK_STATUS_NOLOCK);
        // 发送消息
        String hasLockCar = lockCarMapper.getHasLockCar(lockCar.getCarId());
        if ("1".equals(hasLockCar)) {
            // 取消锁车 发送信息
            this.sendMessageWarningCancelLockCar(lockCar);
        } else if ("2".equals(hasLockCar)) {
            // 继电器取消锁车 发送信息
            this.sendMessageWarningCancelLockCar(lockCar);
        }
    }

    /**
     * 解锁申请
     * @param reqMap
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertAppleLock(Map<String, Object> reqMap) {
        reqMap.put("id", UuidUtil.get32UUID());
        int result = lockCarMapper.insertAppleLock(reqMap);
        reqMap.put("id", UuidUtil.get32UUID());
        if(reqMap.get("type").equals("0")){
            reqMap.put("context","申请解锁");
        }else if(reqMap.get("type").equals("1")){
            reqMap.put("context","申请延迟解锁");
        }
        reqMap.put("client","PC");
        lockCarMapper.updateIsRead(reqMap);
        int insertLockMessage = lockCarMapper.insertLockMessage(reqMap);
        return result;
    }

    @Override
    public int changeMonitorState(Map<String, Object> reqMap) {
        int re1 = lockCarMapper.changeMonitorState(reqMap);
        //更改监控状态(MonitorState)后，需要把锁车记录表中无执行的任务置为执行中断(execute_status由 1 更新为 3)
        int re2 = lockCarMapper.updateThingsIdCarOperationForCMS(reqMap);

        return re1 + re2;
    }

    @Override
    public Map<String, Object> getSmsSendTotalByPhone(String mobilePhone) {
        return lockCarMapper.getSmsSendTotalByPhone(mobilePhone);
    }

    @Override
    public int updateSendTotalByPhone(String mobilePhone) {
        return lockCarMapper.updateSendTotalByPhone(mobilePhone);
    }

    @Override
    public int initSendRecordNumber(String mobilePhone) {
        return lockCarMapper.initSendRecordNumber(mobilePhone);
    }

    /**
     * 发送普通锁车及时消息
     * @param
     */
    private void sendMessageWarningLockCarImmediately(LockCar lockCar) {
        List<Map<String, Object>> carMapList = lockCarMapper.getCarThingsByCarid(lockCar.getCarId());
        if (carMapList.size() > 0) {
            String model = carMapList.get(0).get("model").toString();
            String brand = carMapList.get(0).get("brand").toString();
            String carType = carMapList.get(0).get("car_type").toString();
            int oneLevelDelay = Integer.valueOf(lockCar.getOneLevelDelay());
            int twoLevelDelay = Integer.valueOf(lockCar.getTwoLevelDelay());
            int threeLevelDelay = Integer.valueOf(lockCar.getThreeLevelDelay());

            String content = String.format(SmsUtil.warningLockCarImmediately, carType, model, brand, oneLevelDelay, twoLevelDelay, threeLevelDelay);
            String contentPush = String.format(SmsUtil.warningLockCarImmediatelyPush, carType, model, brand, oneLevelDelay, twoLevelDelay, threeLevelDelay);
            // 发送消息
            this.sendMessage(carMapList, content, contentPush);
        }
    }
    /**
     * 发送继电器锁车
     * @param lockCar
     */
    private void sendMessageWarningRelaylLockCar(LockCar lockCar) {
        List<Map<String, Object>> carMapList = lockCarMapper.getCarThingsByCarid(lockCar.getCarId());
        if (carMapList.size() > 0) {
            String model = carMapList.get(0).get("model").toString();
            String brand = carMapList.get(0).get("brand").toString();
            String carType = carMapList.get(0).get("car_type").toString();
            String adviceName = carMapList.get(0).get("advice_name").toString();

            String content;
            if ("0".equals(lockCar.getLockDelay())) {
                content = String.format(SmsUtil.warningRelaylLockCarImmediately, adviceName, carType, model, brand);
            } else {
                content = String.format(SmsUtil.warningRelaylLockCarDelay, adviceName, carType, model, brand, lockCar.getLockTime());
            }
            // 发送消息
            this.sendMessage(carMapList, content, null);
        }
    }
    /**
     * 发送继电器锁车
     * @param lockCar
     */
    private void sendMessageWarningCancelLockCar(LockCar lockCar) {
        List<Map<String, Object>> carMapList = lockCarMapper.getCarThingsByCarid(lockCar.getCarId());
        if (carMapList.size() > 0) {
            String model = carMapList.get(0).get("model").toString();
            String brand = carMapList.get(0).get("brand").toString();
            String carType = carMapList.get(0).get("car_type").toString();
            String adviceName = carMapList.get(0).get("advice_name").toString();

            String content;
            content = String.format(SmsUtil.warningCancelLockCar, adviceName, carType, model, brand);
            // 发送消息
            this.sendMessage(carMapList, content, null);
        }
    }

    private void sendMessage(List<Map<String, Object>> carMapList, String content, String contentPush){
        if (StringUtils.isBlank(contentPush)) {
            contentPush = content;
        }
        Set<String> oMobilePhonelist = new HashSet<>();
        Set<String> oIdlist = new HashSet<>();
        Set<String> dMobilePhonelist = new HashSet<>();
        Set<String> dIdlist = new HashSet<>();
        Map<String, Object> oMap = new HashMap<>();
        Map<String, Object> dMap = new HashMap<>();
        Map<String, Object> sMap = new HashMap<>();
        Map<String, Object> jrMap = new HashMap<>();

        boolean unlockFlag = content.contains("即将被解锁"); // 如果消息内容内包含“即将被解锁”，则表示激发的为解锁命令，发送给服务商和金融平台的消息内容需要改变

        for (Map<String, Object> carMap : carMapList) {
            List<Map<String, Object>> serverMapList = lockCarMapper.selectUserBySid(carMap.get("s_id").toString());
            List<Map<String, Object>> jrptMapList = lockCarMapper.selectJrUserBySid(carMap.get("s_id").toString());
            if(serverMapList.size() > 0){
                for(Map<String, Object> serverMap : serverMapList){
                    sMap.put("receive_user",serverMap.get("id"));
                    sMap.put("s_id",serverMap.get("s_id"));
                    sMap.put("client", "YD");
                    sMap.put("id",UuidUtil.get32UUID());
                    sMap.put("send_type", unlockFlag ? 106 : 105); // 解锁的消息的类型为 106 ; 锁车类型 105
                    sMap.put("user","system");
                    String serverContent = String.format(SmsUtil.WarningLockCarToServer, carMap.get("advice_name").toString(), carMap.get("car_type").toString(), carMap.get("model").toString(), carMap.get("brand").toString());
                    if(unlockFlag) {  // 如果是解锁消息
                        serverContent = String.format(SmsUtil.WarningUnlockCarToServer, carMap.get("advice_name").toString(), carMap.get("car_type").toString(), carMap.get("model").toString(), carMap.get("brand").toString());
                    }
                    sMap.put("context", serverContent);
                    sMap.put("extra_params", "{'car_lock':''}");
                    SmsUtil.sendSms(serverMap.get("mobile_phone").toString(), serverContent);
                    jiguangPush.jiguangPush(serverMap.get("id").toString(), serverContent, PushConstants.KEY_JUMP_URL,"/car");
                    messageRecordDao.addMessageRecord(sMap);
                };
            }
            if(jrptMapList.size() > 0){
                for(Map<String, Object> jrptMap : jrptMapList){
                    jrMap.put("receive_user",jrptMap.get("id"));
                    jrMap.put("s_id",jrptMap.get("s_id"));
                    jrMap.put("client", "YD");
                    jrMap.put("id",UuidUtil.get32UUID());
                    jrMap.put("send_type", unlockFlag ? 106 : 105); // 解锁的消息的类型为 106 ; 锁车类型 105
                    jrMap.put("user","system");
                    String jrContent = String.format(SmsUtil.WarningLockCarToJrpt, carMap.get("advice_name").toString(), carMap.get("car_type").toString(), carMap.get("model").toString(), carMap.get("brand").toString());
                    if(unlockFlag) {  // 如果是解锁消息
                        jrContent = String.format(SmsUtil.WarningUnlockCarToJrpt, carMap.get("advice_name").toString(), carMap.get("car_type").toString(), carMap.get("model").toString(), carMap.get("brand").toString());
                    }
                    jrMap.put("context", jrContent);
                    jrMap.put("extra_params", "{'car_lock':''}");
                    SmsUtil.sendSms(jrptMap.get("mobile_phone").toString(), jrContent);
                    jiguangPush.jiguangPush(jrptMap.get("id").toString(), jrContent, PushConstants.KEY_JUMP_URL,"/car");
                    messageRecordDao.addMessageRecord(jrMap);
                };
            }
            if (carMap.get("o_mobile_phone") != null) {
                oMobilePhonelist.add(carMap.get("o_mobile_phone").toString());
            }
            if (carMap.get("o_id") != null) {
                oIdlist.add(carMap.get("o_id").toString());
                carMap.put("receive_user", carMap.get("o_id"));
                carMap.put("client", "YD");
                carMap.put("id", UuidUtil.get32UUID());
                carMap.put("send_type", unlockFlag ? 106 : 105); // 解锁的消息的类型为 106 ; 锁车类型 105
                carMap.put("user","system");
                carMap.put("context", content);
                carMap.put("extra_params", "{'car_lock':''}");
                oMap.put(carMap.get("o_id").toString(),JSON.toJSONString(carMap));
            }
            if (carMap.get("d_mobile_phone") != null) {
                dMobilePhonelist.add(carMap.get("d_mobile_phone").toString());
            }
            if (carMap.get("d_id") != null) {
                dIdlist.add(carMap.get("d_id").toString());
                carMap.put("receive_user", carMap.get("o_id"));
                carMap.put("client", "YD");
                carMap.put("id", UuidUtil.get32UUID());
                carMap.put("send_type", unlockFlag ? 106 : 105); // 解锁的消息的类型为 106 ; 锁车类型 105
                carMap.put("user","system");
                carMap.put("context", content);
                carMap.put("extra_params", "{'car_lock':''}");
                dMap.put(carMap.get("d_id").toString(),JSON.toJSONString(carMap));
            }

        }
        // 给车主发送 短信和app消息推送
        oMobilePhonelist.forEach(oMobilePhone -> SmsUtil.sendSms(oMobilePhone, content));
        String finalContentPush = contentPush;
        oIdlist.forEach(oId -> jiguangPush.jiguangPush(oId, finalContentPush, PushConstants.KEY_JUMP_URL,"/car"));
        oIdlist.forEach(oId -> messageRecordDao.addMessageRecord(JSON.parseObject(oMap.get(oId).toString())));
        // 给司机发送
        dMobilePhonelist.forEach(dMobilePhone -> SmsUtil.sendSms(dMobilePhone, content));
        String finalContentPush1 = contentPush;
        dIdlist.forEach(dId -> jiguangPush.jiguangPush(dId, finalContentPush1, PushConstants.KEY_JUMP_URL,"/car"));
        dIdlist.forEach(dId -> messageRecordDao.addMessageRecord(JSON.parseObject(dMap.get(dId).toString())));
    }


    /**
     * 发送解锁码
     * @param carId
     */
    private void sendUnlockCode(String carId) {
        List<Map<String, Object>> carMapList = lockCarMapper.getCarThingsByCarid(carId);
        if (carMapList.size() > 0) {
            String model = carMapList.get(0).get("model").toString();
            String brand = carMapList.get(0).get("brand").toString();
            String carType = carMapList.get(0).get("car_type").toString();
            String thingsId = carMapList.get(0).get("things_id").toString();
            String unlockCode = String.format("%04d", getSecurityCode(thingsId));
            System.out.println("车id：" + carId + "解锁码：" + unlockCode);

            String content = String.format(SmsUtil.warningUnlockCode, carType, model, brand, unlockCode);

            Set<String> oMobilePhonelist = new HashSet<>();
            Set<String> dMobilePhonelist = new HashSet<>();

            for (Map<String, Object> carMap : carMapList) {
                if (carMap.get("o_mobile_phone") != null) {
                    oMobilePhonelist.add(carMap.get("o_mobile_phone").toString());
                }
                if (carMap.get("d_mobile_phone") != null) {
                    dMobilePhonelist.add(carMap.get("d_mobile_phone").toString());
                }
            }
            // 给车主发送安全码 短信和app消息推送
            oMobilePhonelist.forEach(oMobilePhone -> SmsUtil.sendSms(oMobilePhone, content));
            // 给司机发送安全码
            dMobilePhonelist.forEach(dMobilePhone -> SmsUtil.sendSms(dMobilePhone, content));
        }
    }

    private int getSecurityCode(String thingsNo) {
        if (!thingsNo.contains("170")) {
            return 0;
        }
        thingsNo = "0" + thingsNo;
        LocalDateTime dateTime = LocalDateTime.now();
        String formatDate = dateTime.format(DateTimeFormatter.ofPattern("yyMMddHHmm"));
        int num = Integer.valueOf(formatDate) % 5;
        if (num <= 4) {
            formatDate = formatDate.substring(0, formatDate.length() - 1) + 0;
        } else {
            formatDate = formatDate.substring(0, formatDate.length() - 1) + 5;
        }
        String str1 = thingsNo + formatDate;
        return this.getCrc16(str1);
    }

    private int getCrc16(String str) {
        int len = str.length();
        // 预置 1 个 16 位的寄存器为十六进制FFFF, 称此寄存器为 CRC寄存器。
        int crc = 0xFFFF;
        int i, j;
        for (i = 0; i < (len / 2); i++) {
            // 把第一个 8 位二进制数据 与 16 位的 CRC寄存器的低 8 位相异或, 把结果放于 CRC寄存器
            crc ^= Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16);
            for (j = 0; j < 8; j++) {
                // 把 CRC 寄存器的内容右移一位( 朝低位)用 0 填补最高位, 并检查右移后的移出位
                if ((crc & 0x01) > 0) {
                    // 如果移出位为 1, CRC寄存器与多项式A001进行异或
                    crc >>= 1;
                    crc ^= 0xA001;
                } else {
                    // 如果移出位为 0,再次右移一位
                    crc >>= 1;
                }
            }
        }
        //crc = (crc << 8) + (crc >> 8);
//        System.out.println(crc / 7);
        return crc / 7;
    }


    /**
     * 通过正则表达式的方式获取字符串中指定字符的个数
     * @param text 指定的字符串
     * @return 指定字符的个数
     */
    private int hasTxtTotoal(String text) {
        // 根据指定的字符构建正则
        Pattern pattern = Pattern.compile("%s");
        // 构建字符串和正则的匹配
        Matcher matcher = pattern.matcher(text);
        int count = 0;
        // 循环依次往下匹配
        while (matcher.find()){ // 如果匹配,则数量+1
            count++;
        }
        return  count;
    }

    /**
     * 车辆命令插入
     *
     * @return
     */
    @Override
    public void thingsIdCarOperation(Map<String, Object> reqMap) {
        // 前端传递过来的 lock_type 为 88(与之前的代码逻辑不再混淆，故重新定义为 88),则表示为周期锁车，需要更新 t_s_ss_lock_thingsid_car 表 (lock_type = 2)
        if(Orgin.getIntValue(reqMap, "lock_type") == 88) {
            reqMap.put("id", UuidUtil.get32UUID());
            reqMap.put("lock_type", 2);

            // 构造周期锁车的开始时间 lock_cycle_datetime
            Calendar newTime = Calendar.getInstance();
            newTime.setTime(new Date());
            newTime.add(Calendar.SECOND,Integer.parseInt(reqMap.get("lock_cycle").toString())); // 日期时间加 x秒
            reqMap.put("lock_cycle_datetime", newTime.getTime());

            lockCarMapper.updateThingsIdCarOperationStatusTo2(reqMap);
            lockCarMapper.thingsIdCarLockCycleOperation(reqMap);
            lockCarMapper.updateCarIsLoeckByCarId(Orgin.getString(reqMap, "car_id"), Orgin.getString(reqMap, "isLocked"));
            if (Orgin.getIntValue(reqMap, "smsStatus") == 1) {
                // hasLockCar   状态值 0-没有锁车功能 1-普通锁车 2-继电器锁车
                String hasLockCar = lockCarMapper.getHasLockCar(Orgin.getString(reqMap, "car_id"));
                if ("1".equals(hasLockCar)) {
                    if (Orgin.getIntValue(reqMap, "lock_type") == 0 || Orgin.getIntValue(reqMap, "lock_type") == 1) {
                        // 限速(一级、二级限速)提醒
                        this.sendMessageWarningLimitSpeed(reqMap);
                    } else if (Orgin.getIntValue(reqMap, "lock_type") == 2) {
                        // 锁车
                        this.sendMessageWarningLockCar(reqMap);
                        // 解锁
                    } else if (Orgin.getIntValue(reqMap, "lock_type") == 3) {
                        this.sendMessageWarningUnlockCar(reqMap);
                    }
                } else if ("2".equals(hasLockCar)) {
                    if (Orgin.getIntValue(reqMap, "lock_type") == 4) {
                        // 锁车
                        this.sendMessageWarningLockCar(reqMap);
                    } else if (Orgin.getIntValue(reqMap, "lock_type") == 5) {
                        // 解锁
                        this.sendMessageWarningUnlockCar(reqMap);
                    }
                }
            }
            try {
                Map<String, Object> carMap = facilitatorPersonnelRelationDao.selectCar(Orgin.getString(reqMap, "car_id"));
                reqMap.put("car_name", Orgin.getString(carMap, "advice_name"));
                Map<String, Object> serverMap = userDao.getServerInfoBySId(reqMap);
                reqMap.put("s_name", Orgin.getString(serverMap, "user_name"));
                if (Orgin.getIntValue(reqMap, "lock_type") == 0 ||
                        Orgin.getIntValue(reqMap, "lock_type") == 1 ||
                        Orgin.getIntValue(reqMap, "lock_type") == 2 ||
                        Orgin.getIntValue(reqMap, "lock_type") == 4 ||
                        Orgin.getIntValue(reqMap, "lock_type") == 88) {
                    //日志系统操作记录-锁车管理_锁车
                    rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("锁车管理"), Constants.OperationType.getOperationTypeCode("锁车"),
                            Orgin.getString(reqMap, "update_user"), Orgin.getString(reqMap, "user_name"), "", "",
                            Orgin.getString(reqMap, "car_id"), Orgin.getString(reqMap, "car_name"), Orgin.getString(reqMap, "s_id"), Orgin.getString(reqMap, "s_name"), "");
                } else if (Orgin.getIntValue(reqMap, "lock_type") == 3 ||
                        Orgin.getIntValue(reqMap, "lock_type") == 5) {
                    //日志系统操作记录-锁车管理_解锁
                    rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("锁车管理"), Constants.OperationType.getOperationTypeCode("解锁"),
                            Orgin.getString(reqMap, "update_user"), Orgin.getString(reqMap, "user_name"), "", "",
                            Orgin.getString(reqMap, "car_id"), Orgin.getString(reqMap, "car_name"), Orgin.getString(reqMap, "s_id"), Orgin.getString(reqMap, "s_name"), "");
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            }
        } else { // 一级、二级、锁车
            Integer lockCar = lockCarMapper.getThingsIdCarOperation(reqMap);
            if (lockCar != 0){
                lockCarMapper.updateThingsIdCarOperation(reqMap);
            }
            if (!reqMap.containsKey("lock_speed")) {
                reqMap.put("lock_speed", "");
            }
            if (!reqMap.containsKey("lock_torque")) {
                reqMap.put("lock_torque", "");
            }
            engineLockCarService.handleMessage(reqMap);
            reqMap.put("id", UuidUtil.get32UUID());
            lockCarMapper.thingsIdCarOperation(reqMap);
            lockCarMapper.updateCarIsLoeckByCarId(Orgin.getString(reqMap, "car_id"), Orgin.getString(reqMap, "isLocked"));
            if (Orgin.getIntValue(reqMap, "smsStatus") == 1) {
                // hasLockCar   状态值 0-没有锁车功能 1-普通锁车 2-继电器锁车
                String hasLockCar = lockCarMapper.getHasLockCar(Orgin.getString(reqMap, "car_id"));
                if ("1".equals(hasLockCar)) {
                    if (Orgin.getIntValue(reqMap, "lock_type") == 0 || Orgin.getIntValue(reqMap, "lock_type") == 1) {
                        // 限速(一级、二级限速)提醒
                        this.sendMessageWarningLimitSpeed(reqMap);
                    } else if (Orgin.getIntValue(reqMap, "lock_type") == 2) {
                        // 锁车
                        this.sendMessageWarningLockCar(reqMap);
                        // 解锁
                    } else if (Orgin.getIntValue(reqMap, "lock_type") == 3) {
                        this.sendMessageWarningUnlockCar(reqMap);
                    }
                } else if ("2".equals(hasLockCar)) {
                    if (Orgin.getIntValue(reqMap, "lock_type") == 4) {
                        // 锁车
                        this.sendMessageWarningLockCar(reqMap);
                    } else if (Orgin.getIntValue(reqMap, "lock_type") == 5) {
                        // 解锁
                        this.sendMessageWarningUnlockCar(reqMap);
                    }
                }
            }
            try {
                Map<String, Object> carMap = facilitatorPersonnelRelationDao.selectCar(Orgin.getString(reqMap, "car_id"));
                reqMap.put("car_name", Orgin.getString(carMap, "advice_name"));
                if(!reqMap.get("user_name").toString().equals("系统平台")) {
                    Map<String, Object> serverMap = userDao.getServerInfoBySId(reqMap);
                    reqMap.put("s_name", Orgin.getString(serverMap, "user_name"));
                }else{
                    reqMap.put("s_name", "系统平台");
                }
                if (Orgin.getIntValue(reqMap, "lock_type") == 0 ||
                        Orgin.getIntValue(reqMap, "lock_type") == 1 ||
                        Orgin.getIntValue(reqMap, "lock_type") == 2 ||
                        Orgin.getIntValue(reqMap, "lock_type") == 4) {
                    //日志系统操作记录-锁车管理_锁车
                    rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("锁车管理"), Constants.OperationType.getOperationTypeCode("锁车"),
                            Orgin.getString(reqMap, "update_user"), Orgin.getString(reqMap, "user_name"), "", "",
                            Orgin.getString(reqMap, "car_id"), Orgin.getString(reqMap, "car_name"), Orgin.getString(reqMap, "s_id"), Orgin.getString(reqMap, "s_name"), "");
                } else if (Orgin.getIntValue(reqMap, "lock_type") == 3 ||
                        Orgin.getIntValue(reqMap, "lock_type") == 5) {
                    //日志系统操作记录-锁车管理_解锁
                    rabbitMQCustomer.operationLogMq(Constants.OperationModel.getOperationModelCode("锁车管理"), Constants.OperationType.getOperationTypeCode("解锁"),
                            Orgin.getString(reqMap, "update_user"), Orgin.getString(reqMap, "user_name"), "", "",
                            Orgin.getString(reqMap, "car_id"), Orgin.getString(reqMap, "car_name"), Orgin.getString(reqMap, "s_id"), Orgin.getString(reqMap, "s_name"), "");
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            }
        }
    }

    /**
     * 发送普通限速及时消息
     * @param
     */
    private void sendMessageWarningLimitSpeed(Map<String, Object> reqMap) {
        List<Map<String, Object>> carMapList = lockCarMapper.getLockCarThingsByCarId(Orgin.getString(reqMap, "car_id"));
        if (carMapList.size() > 0) {
            String model = carMapList.get(0).get("model").toString();
            String brand = carMapList.get(0).get("brand").toString();
            String carType = carMapList.get(0).get("car_type").toString();

            String content = String.format(SmsUtil.WarningLimitSpeed, carType, model, brand);
            // 发送消息
            this.sendMessage(carMapList, content, content);
        }
    }

    /**
     * 发送锁车及时消息
     * @param
     */
    private void sendMessageWarningLockCar(Map<String, Object> reqMap) {
        List<Map<String, Object>> carMapList = lockCarMapper.getLockCarThingsByCarId(Orgin.getString(reqMap, "car_id"));
        if (carMapList.size() > 0) {
            String model = carMapList.get(0).get("model").toString();
            String brand = carMapList.get(0).get("brand").toString();
            String carType = carMapList.get(0).get("car_type").toString();

            String content = String.format(SmsUtil.WarningLockCar, carType, model, brand);
            // 发送消息
            this.sendMessage(carMapList, content, content);
        }
    }

    /**
     * 发送解锁及时消息
     * @param
     */
    private void sendMessageWarningUnlockCar(Map<String, Object> reqMap) {
        List<Map<String, Object>> carMapList = lockCarMapper.getLockCarThingsByCarId(Orgin.getString(reqMap, "car_id"));
        if (carMapList.size() > 0) {
            String model = carMapList.get(0).get("model").toString();
            String brand = carMapList.get(0).get("brand").toString();
            String carType = carMapList.get(0).get("car_type").toString();

            String content = String.format(SmsUtil.WarningUnlockCar, carType, model, brand);
            // 发送消息
            this.sendMessage(carMapList, content, content);
        }
    }

    /**
     * 锁车记录查询
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> thingsIdCarRecord(Map<String, Object> reqMap) {
        List<Map<String, Object>> thingsIdCarRecord = lockCarMapper.thingsIdCarRecord(reqMap);
        return thingsIdCarRecord;
    }

    /**
     * 周期锁车命令获取
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> getCycleLockThingsIdList(Map<String, Object> reqMap) {
        List<Map<String, Object>> list = lockCarMapper.getCycleLockThingsIdList(reqMap);

        return list;
    }

    /**
     * 更新周期锁车的信息的执行状态
     * @param reqMap
     * @return
     */
    @Override
    public int updateCycleLockThingsStatus(Map<String, Object> reqMap) {
        int result = lockCarMapper.updateCycleLockThingsStatus(reqMap);
        return result;
    }

    /**
     * 更新周期锁车的车辆设备的锁车状态
     * @param reqMap
     * @return
     */
    @Override
    public int updateCarStatusForCycleLock(Map<String, Object> reqMap) {
        int result = lockCarMapper.updateCarStatusForCycleLock(reqMap);
        return result;
    }

    /**
     * 更新周期锁车的信息的执行状态 - 用于APP解锁页面
     * @param reqMap
     * @return
     */
    @Override
    public int updateCycleLockThingsStatusForUnlock(Map<String, Object> reqMap) {
        int result = lockCarMapper.updateCycleLockThingsStatusForUnlock(reqMap);
        return result;
    }

    @Override
    public Map<String, Object> thingsIdCarRecordNew(Map<String, Object> reqMap) {
        Map<String, Object> thingsIdCarRecordNew = lockCarMapper.thingsIdCarRecordNew(reqMap);
        return thingsIdCarRecordNew;
    }

    @Override
    public void bluetoothUnLock(Map<String, Object> reqMap) {
        List<Map<String, Object>> maps = lockCarMapper.bluetoothUnLock(reqMap);
        String thingsId = Orgin.getString(maps.get(0), "things_id");
        lockCarMapper.updateStatus(thingsId);
        String date = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDateTime.now());
        String message=date.substring(3,8)+".zoweunion"+thingsId;
        String md5Message = MD5.md5(message);
        String substring = md5Message.substring(md5Message.length() - 6);
        String content = String.format(SmsUtil.bluetoothUnLock,
                maps.get(0).get("advice_name").toString(),substring);
        this.sendMessage(maps, content, null);
    }

    @Override
    public List<ThingsIdCarRecordBean> exportThingsIdCarRecord(Map<String, Object> reqMap) {
        List<ThingsIdCarRecordBean> exportThingsIdCarRecord = lockCarMapper.exportThingsIdCarRecord(reqMap);
        return exportThingsIdCarRecord;
    }

}
